package com.halixun.d2app.ui.fragment;


import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.JsonObject;
import com.halixun.d2app.R;
import com.halixun.d2app.adapter.OrderDetailAdapter;
import com.halixun.d2app.base.BaseFragment;
import com.halixun.d2app.base.BaseResult;
import com.halixun.d2app.bean.OrderDetais;
import com.halixun.d2app.dialog.RefundDialogFragment;
import com.halixun.d2app.net.CreateRequestEntity;
import com.halixun.d2app.net.errer.ResultVerifier;
import com.halixun.d2app.utils.DensityUtil;
import com.halixun.d2app.utils.RequestDataUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class BillWaterFragment extends BaseFragment implements View.OnClickListener, OnRefreshLoadmoreListener, OrderDetailAdapter.OrderDetailListener {

    private static final String KEY_TAG = "key_tag";

    private List<OrderDetais.Item1Bean.ListBean> mListBeans;

    private RecyclerView mRecyclerView;

    private OrderDetailAdapter mAdapter;

    private TimePickerView pvTime;

    private TextView pickerTimeView;

    private Date mDate;

    private TextView startTime, endTime;

    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

    /**
     * ==-1,未点击；==0，点击开始时间；==1，点击结束时间.
     */
    private int clickViewIndex = -1;

    private Date pickerTimeViewData;

    /**
     * ==0,刷新；==1，上拉加载
     */
    private int loadState = 0;

    private final int pagerSize = 20;

    private int pagerIndex = 0;

    private SmartRefreshLayout mSmartRefreshLayout;

    private View noData;

    public static BaseFragment getInstance(String tag) {
        BillWaterFragment f = new BillWaterFragment();
        Bundle params = new Bundle();
        params.putString(KEY_TAG, tag);
        f.setArguments(params);
        return f;
    }

    public BillWaterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_bill_water, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setAdapter();
        initData();
        mSmartRefreshLayout.autoRefresh();
    }

    private void initData() {
        mDate = new Date();
        startTime.setText(sf.format(mDate));
        endTime.setText(sf.format(mDate));
    }

    private void setAdapter() {
        mListBeans = new ArrayList<>();
        mAdapter = new OrderDetailAdapter(mListBeans);
        mAdapter.setOnOrderDetailListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void initView() {
        noData = mRootView.findViewById(R.id.noData);
        mSmartRefreshLayout = mRootView.findViewById(R.id.mSmartRefreshLayout);
        mSmartRefreshLayout.setEnableRefresh(true);
        mSmartRefreshLayout.setEnableLoadmore(true);
        startTime = mRootView.findViewById(R.id.startTime);
        endTime = mRootView.findViewById(R.id.endTime);
        mRecyclerView = mRootView.findViewById(R.id.mRecyclerView);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildAdapterPosition(view);
                if (index + 1 == mListBeans.size()) {
                    outRect.bottom = DensityUtil.dp2px(mContext, (float) 4);
                }
                outRect.top = 0;
                outRect.right = 0;
                outRect.left = 0;
            }
        });
    }

    @Override
    protected void setListeners() {
        mRootView.findViewById(R.id.startTimeLayout).setOnClickListener(this);
        mRootView.findViewById(R.id.endTimeLayout).setOnClickListener(this);
        mRootView.findViewById(R.id.query).setOnClickListener(this);
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(this);
    }

    private void getData() {
        JsonObject object = new JsonObject();
        object.addProperty("beginTime", startTime.getText().toString() + "T00:00:00+08:00");
        object.addProperty("endTime", endTime.getText().toString() + "T23:59:59+08:00");
        object.addProperty("orderState", -2);
        object.addProperty("orderType", -2);
        object.addProperty("search", "");
        object.addProperty("pageIndex", pagerIndex == 0 ? 1 : pagerIndex);
        object.addProperty("pageSize", pagerSize);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), object.toString());
        CreateRequestEntity.getWebService().getOrderList(body, RequestDataUtils.getRequestDataParam(mContext)).enqueue(new Callback<BaseResult<OrderDetais>>() {
            @Override
            public void onResponse(Call<BaseResult<OrderDetais>> call, Response<BaseResult<OrderDetais>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    if (loadState == 0) {
                        pagerIndex = 1;
                        mListBeans.clear();
                        mSmartRefreshLayout.finishRefresh(true);
                    } else {
                        mSmartRefreshLayout.finishLoadmore(true);
                    }
                    if (response.body().Data.getItem1() != null && response.body().Data.getItem1().getList() != null) {
                        mListBeans.addAll(response.body().Data.getItem1().getList());
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    if (loadState == 1) {
                        mSmartRefreshLayout.finishLoadmore(false);
                        if (pagerIndex >= 1) {
                            pagerIndex -= 1;
                        } else {
                            pagerIndex = 0;
                        }
                    } else {
                        pagerIndex = 0;
                        mListBeans.clear();
                        mAdapter.notifyDataSetChanged();
                        mSmartRefreshLayout.finishRefresh(false);
                    }
                    ResultVerifier.serceErrers(response);
                }
                noData.setVisibility(mListBeans.size() > 0 ? View.GONE : View.VISIBLE);
            }

            @Override
            public void onFailure(Call<BaseResult<OrderDetais>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                if (loadState == 1) {
                    mSmartRefreshLayout.finishLoadmore(false);
                    if (pagerIndex > 1) {
                        pagerIndex -= 1;
                    } else {
                        pagerIndex = 1;
                    }
                } else {
                    mSmartRefreshLayout.finishRefresh(false);
                }
                noData.setVisibility(mListBeans.size() > 0 ? View.GONE : View.VISIBLE);
            }
        });
    }

    private void showTimeDialog() {
        if (null == pvTime) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            pvTime = new TimePickerBuilder(mContext, null)
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setSubmitColor(getResources().getColor(R.color.commot_color))
                    .setCancelColor(getResources().getColor(R.color.commot_color))
                    .setLayoutRes(R.layout.select_pickerview_layout, new CustomListener() {
                        @Override
                        public void customLayout(View v) {
                            pickerTimeView = v.findViewById(R.id.pickerTime);
                            v.findViewById(R.id.pickerCancel).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null != pvTime) {
                                        pvTime.dismiss();
                                    }
                                }
                            });
                            v.findViewById(R.id.pickerConfirm).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null == pickerTimeViewData) {
                                        pickerTimeViewData = new Date();
                                    }
                                    mDate = pickerTimeViewData;
                                    if (clickViewIndex == 0) {
                                        startTime.setText(sf.format(mDate));
                                    } else {
                                        endTime.setText(sf.format(mDate));
                                    }
                                    if (null != pvTime) {
                                        pvTime.dismiss();
                                    }
                                }
                            });
                        }
                    })
                    .setTimeSelectChangeListener(date -> {
                        this.pickerTimeViewData = date;
                        if (null != pickerTimeView) {
                            pickerTimeView.setText(sf.format(date));
                        }
                    })
                    .setContentTextSize(10)
                    .isDialog(true)
                    .setTextColorCenter(Color.parseColor("#FF4B01"))
                    .setTextColorOut(Color.parseColor("#aaaaaa"))
                    .setOutSideCancelable(false)
                    .setRangDate(null, calendar)
                    .setDate(calendar)
                    .build();
        }
        pvTime.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.endTimeLayout:
                clickViewIndex = 1;
                showTimeDialog();
                break;
            case R.id.startTimeLayout:
                clickViewIndex = 0;
                showTimeDialog();
                break;
            case R.id.query:
                mSmartRefreshLayout.autoRefresh();
                break;
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        loadState = 1;
        pagerIndex += 1;
        getData();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        loadState = 0;
        pagerIndex = 0;
        getData();
    }

    @Override
    public void onOrderDetailListener(int position) {
        if (position < mListBeans.size()) {
            OrderDetais.Item1Bean.ListBean info = mListBeans.get(position);
            RefundDialogFragment.getInstance(info.getOrderMoney(), info.getOrderId())
                    .setOnRefundDialogListener((momey, orderId, password) -> refund(momey, orderId, password, position))
                    .show(getChildFragmentManager(), "RefundDialogFragment");
        }
    }

    private void refund(String momey, String orderId, String password, int position) {
        showProgressDialog("退款操作中...");
        JsonObject object = new JsonObject();
        object.addProperty("orderId", orderId);
        object.addProperty("password", password);
        object.addProperty("refundMoney", momey);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), object.toString());
        CreateRequestEntity.getWebService().refund(body, RequestDataUtils.getRequestDataParam(mContext)).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    OrderDetais.Item1Bean.ListBean info = mListBeans.get(position);
                    info.setOrderState(-1);
                    mAdapter.notifyItemChanged(position);
                } else {
                    ResultVerifier.serceErrers(response);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }
}
